package com.seeyon.apps.ext.cop.button.login;

import bsh.StringUtil;
import com.seeyon.apps.ext.cop.button.util.BaseDaoSqlOA;
import com.seeyon.ctp.common.authenticate.domain.LoginUtil;
import com.seeyon.ctp.common.constants.Constants;
import com.seeyon.ctp.common.constants.LoginConstants;
import com.seeyon.ctp.login.AbstractLoginAuthentication;
import com.seeyon.ctp.login.LoginAuthenticationException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import snail.common.utils.db.DBHelper;
import snail.common.utils.db.DataSourceHelper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class CustomLoginAuthentication extends AbstractLoginAuthentication {

    private static final Log LOG = LogFactory.getLog(CustomLoginAuthentication.class);

    private  String url = "jdbc:mysql://10.211.55.2:3306/ego?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8";// 连接URL字符串
    private  String user = "root";// 数据库用户名
    private  String mPassword = "Mysql123456";// 用户密码
    @Override
    public String[] authenticate(HttpServletRequest request, HttpServletResponse httpServletResponse) throws LoginAuthenticationException {

        try {
            String username = request.getParameter(LoginConstants.USERNAME);// 用户名
            String password = request.getParameter(LoginConstants.PASSWORD);// 密码
            LOG.info("输入的账号：" + username + "输入的密码" + password);
            if (username == null || password == null) {
                return null;
            }
            //登录方式，判断是否移动应用登陆
            String userAgentFrom = request.getParameter(Constants.LOGIN_USERAGENT_FROM);
            boolean fromMobile = Constants.login_useragent_from.mobile.name().equals(userAgentFrom) || LoginUtil.isFromM1(userAgentFrom);

            if (check(username, password)) {
                username = selectIdYWYOA(username);
                return new String[]{username, password};
            }
            return null;
        }catch(Throwable e){

            LOG.error("登陆认证失败, error: " + e.getMessage(), e);

            return null;
        }
    }

    private boolean check(String username, String password) {



        // 登录认证逻辑，用户名和密码正确时返回true即可
        DataSource ds = DataSourceHelper.getMySQL6XDatasource(url, user, mPassword);
        DBHelper dbhelper = DBHelper.getInstance(ds);
        try {
            String dbPassword = dbhelper.queryString("select password from users where login = ?", username);
            if (dbPassword != null){
                String a = selectIdYWYOA(username);
                LOG.info("获取到的登陆名：" + a);
                if (password.equals(dbPassword) && (a != null && !a.equals(""))) {
                    return true;
                }
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return false;
    }
    public String selectIdYWYOA(String value) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        String loginName = "";
        BaseDaoSqlOA dao = new BaseDaoSqlOA();
        if (value != null) {
            try {
                conn = dao.getConnection();
                String sql = "select b.LOGIN_NAME from ORG_MEMBER a LEFT JOIN ORG_PRINCIPAL b on a.id = b.MEMBER_ID  where a.EXT_ATTR_2 = ? and a.is_enable = 1";
                pstmt = conn.prepareStatement(sql);
                pstmt.setString(1, value);
                rs = pstmt.executeQuery();
                while (rs.next()) {
                    loginName = rs.getString("LOGIN_NAME");
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                dao.closeAll(conn, pstmt, rs);
            }
            return loginName;
        }
        return null;

    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getmPassword() {
        return mPassword;
    }

    public void setmPassword(String mPassword) {
        this.mPassword = mPassword;
    }
}
